<!-- 商品发布 - 会员折扣 -->
<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="130px" :disabled="isDetail">
    <div
      class="p-10px border-rd-5px mb-20px border-1px bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      会员折扣设置
    </div>
    <el-form-item label="会员折扣" prop="memberDiscount">
      <div class="w-100%">
        <el-radio-group
          v-model="formData.memberDiscount!.selectId"
          @change="onMemberchange('memberDiscount')"
        >
          <el-radio :value="0">不支持</el-radio>
          <el-radio :value="1">系统默认</el-radio>
          <el-radio :value="2">多规格会员等级</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    <template v-if="formData.memberDiscount?.selectId == 2">
      <el-form-item v-if="!formData.specType">
        <SkuListMemberShip
          ref="skuListMembershipRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="memberDiscountRuleConfig"
          :rule-type="'memberDiscount'"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListMemberShip
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-type="'memberDiscount'"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListMemberShip
            ref="skuListMembershipRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="memberDiscountRuleConfig"
            :rule-type="'memberDiscount'"
          />
        </el-form-item>
      </template>
    </template>

    <el-form-item label="付费会员折扣" prop="paidmemberDiscount">
      <div class="w-100%">
        <el-radio-group
          v-model="formData.paidmemberDiscount!.selectId"
          @change="onPaidMemberchange('paidmemberDiscount')"
        >
          <el-radio :value="0">不支持</el-radio>
          <el-radio :value="1">系统默认</el-radio>
          <el-radio :value="2">多规格会员等级</el-radio>
        </el-radio-group>
      </div>
    </el-form-item>
    <template v-if="formData.paidmemberDiscount?.selectId == 2">
      <el-form-item v-if="!formData.specType">
        <SkuListPaidMemberShip
          ref="skuListPaidMembershipRef"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="paidmemberDiscountRuleConfig"
          :rule-type="'paidmemberDiscount'"
        />
      </el-form-item>
      <template v-if="formData.specType && propertyList.length > 0">
        <el-form-item v-if="!isDetail" label="批量设置">
          <SkuListPaidMemberShip
            :is-batch="true"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-type="'paidmemberDiscount'"
          />
        </el-form-item>
        <el-form-item label="规格列表">
          <SkuListPaidMemberShip
            ref="skuListPaidMembershipRef"
            :is-detail="isDetail"
            :prop-form-data="formData"
            :property-list="propertyList"
            :rule-config="paidmemberDiscountRuleConfig"
            :rule-type="'paidmemberDiscount'"
          />
        </el-form-item>
      </template>
    </template>
  </el-form>
</template>
<script lang="ts" setup>
import type { Spu } from '@/api/mall/product/spu'
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { copyValueToTarget } from '@/utils'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig,
  SkuListMemberShip,
  SkuListPaidMemberShip
} from '@/views/mall/product/spu/components/index'

defineOptions({ name: 'ProductPermissionForm' })
const memberDiscountRuleConfig: RuleConfig[] = []
const paidmemberDiscountRuleConfig: RuleConfig[] = []
let membershipLevelType = getIntDictOptions(DICT_TYPE.METON_MEMBERSHIP_LEVEL)
let paidMembershipLevelType = getIntDictOptions(DICT_TYPE.METON_PAID_MEMBERSHIP_LEVEL)

membershipLevelType.forEach((ele) => {
  memberDiscountRuleConfig.push({
    name: `memberDiscount${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
})
paidMembershipLevelType.forEach((ele) => {
  paidmemberDiscountRuleConfig.push({
    name: `paidmemberDiscount${ele.value}`,
    rule: (arg) => arg >= 0 && arg != '',
    message: ''
  })
})
const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  activeName: propTypes.string.def(''),
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const formRef = ref() // 表单Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListMembershipRef = ref() // 商品属性列表 Ref
const skuListPaidMembershipRef = ref()
// 表单数据
const formData = ref<Spu>({
  specType: false, // 商品规格
  skus: [],
  memberDiscount: {
    selectId: 0,
    ruleList: []
  },
  paidmemberDiscount: {
    selectId: 0,
    ruleList: []
  }
})
// 表单规则
const rules = reactive({})
/**会员选择改变 */
const onMemberchange = (type: any) => {
  formData.value.skus?.forEach((element) => {
    membershipLevelType.forEach((ele) => {
      element[`${type}${ele.value}`] = undefined
      element[`${type}${ele.value}ruleType`] = 0
    })
  })
}
const onPaidMemberchange = (type: any) => {
  formData.value.skus?.forEach((element) => {
    paidMembershipLevelType.forEach((ele) => {
      element[`${type}${ele.value}`] = undefined
      element[`${type}${ele.value}ruleType`] = 0
    })
  })
}

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData.value, data)
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    skuListMembershipRef.value?.validateSku()
    skuListPaidMembershipRef.value?.validateSku()
    await unref(formRef)?.validate()
    formData.value.memberDiscount!.ruleList = []
    formData.value.paidmemberDiscount!.ruleList = []

    formData.value.skus?.forEach((ele) => {
      //会员折扣
      formData.value.memberDiscount!.ruleList?.push({
        skuSpecList: ele.properties,
        memberList: membershipLevelType.map((item) => {
          return {
            shipLevel: item.value,
            ruleValue: ele[`memberDiscount${item.value}`],
            ruleType: ele[`memberDiscount${item.value}ruleType`]
          }
        })
      })
      // 付费会员折扣
      formData.value.paidmemberDiscount!.ruleList?.push({
        skuSpecList: ele.properties,
        memberList: membershipLevelType.map((item) => {
          return {
            shipLevel: item.value,
            ruleValue: ele[`paidmemberDiscount${item.value}`],
            ruleType: ele[`paidmemberDiscount${item.value}ruleType`]
          }
        })
      })
    })

    // 校验通过更新数据
    Object.assign(props.propFormData, formData.value)
  } catch (e) {
    message.error('【会员折扣设置】不完善，请填写相关信息')
    emit('update:activeName', 'vipDiscounts')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
</script>
